package com.xk.springboot.controller;


import com.xk.springboot.dto.ResponseData;
import com.xk.springboot.dto.ResultData;
import com.xk.springboot.task.AsyncTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author:Teacher黄
 * @date:Created at 2020/04/13
 */
@RestController
@RequestMapping("/async")
public class AsyncController {

    /**
     * 异步任务类
     */
    @Autowired
    private AsyncTask asyncTask;

    @GetMapping("/test01")
    public ResultData test01() throws InterruptedException {
        // 测试主线程耗时
        // 开始时间
        long start = System.currentTimeMillis();
        // 调用异步方法
        asyncTask.task01();
        asyncTask.task02();
        asyncTask.task03();
        // 结束时间
        long end = System.currentTimeMillis();
        System.out.println("主线程耗时:"+(end-start));
        return ResponseData.success("主线程耗时:"+(end-start));
    }

    @GetMapping("/test02")
    public ResultData test02() throws InterruptedException, ExecutionException {
        // 测试主线程耗时
        // 开始时间
        long start = System.currentTimeMillis();
        // 调用带返回值的异步方法
        Future<String> res4 = asyncTask.task04();
        Future<String> res5 = asyncTask.task05();
        Future<String> res6 = asyncTask.task06();
        // 确保异步任务都完成, 死循环
        while (true){
            if(res4.isDone() && res5.isDone() && res6.isDone()){
                break;
            }
        }
        // 输出异步任务执行结果
        System.out.println(res4.get());
        System.out.println(res5.get());
        System.out.println(res6.get());

        // 结束时间
        long end = System.currentTimeMillis();
        System.out.println("主线程耗时:"+(end-start));
        return ResponseData.success("主线程耗时:"+(end-start));
    }


}
